<?php
/**
 * 普通的工具方法
 * Created by PhpStorm.
 * User: lee
 * Date: 2020/4/1
 */

// 根据版本获取路由指向
if (! function_exists('getRouterController')) {
    function getRouterController($controllerName, $actionName)
    {
        $request = app('request');
        $appVersion = $request->header('version', env('APP_VERSION', '1.0.0'));

        $basePath = '\App\Http\Controllers\\';
        $versionPath = 'Api\V'.str_replace('.', '_', $appVersion).'\\';
        $controllerPath = $basePath.$versionPath.$controllerName;
        //存在对应版本的类文件则直接返回
        if (class_exists($controllerPath)) {
            return $versionPath.$controllerName.'@'.$actionName;
        }
        //不存在的话自动降级查找
        //原则上版本需放到数据库或Redis之类的地方存储起来进行管理
        $versionHistory = explode(',', env('APP_VERSION_HISTORY', '1.0.0'));
        $index = array_search($appVersion, $versionHistory);
        if (isset($versionHistory[$index - 1])) {
            $versionPath = 'V'.str_replace('.', '_', $versionHistory[$index - 1]).'\\';
            $controllerPath = $basePath.$versionPath.$controllerName;
            if (class_exists($controllerPath)) {
                return $versionPath.$controllerName.'@'.$actionName;
            }
        }
        return $basePath.'EmptyController@index';
    }
}
